/**
 * @Classname RecordNotifyServiceImpl
 * @Description TODO
 * @author Tale-Mi
 * @date 2019/2/17 23:35
 */
package org.tale.mscp.notify.services.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.tale.mscp.notify.MscpNotifyApplication;
import org.tale.mscp.notify.entity.AttAtdRec;
import org.tale.mscp.notify.entity.BrushCard;
import org.tale.mscp.notify.mapper.AttAtdRecMapper;
import org.tale.mscp.notify.mapper.BrushCardMapper;
import org.tale.mscp.notify.services.IRecordNotifyService;
import org.tale.mscp.notify.utils.Const;
import org.tale.mscp.notify.utils.HttpsUtilsPool;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@DS("master")
public class RecordNotifyServiceImpl implements IRecordNotifyService {
    @Autowired
    private AttAtdRecMapper attAtdRecMapper;
    @Autowired
    private BrushCardMapper brushCardMapper;

    private static final Logger logger = LoggerFactory.getLogger(MscpNotifyApplication.class);

    @Override
//    @DS("kqKemi")
    public List<AttAtdRec> getKemiRecord(LocalDate startDate, LocalDate endDate, String name, String userId) {
//        return attAtdRecMapper.selectList(new LambdaQueryWrapper<AttAtdRec>().gt(AttAtdRec::getRecDate, startDate).lt(AttAtdRec::getRecDate, endDate).eq(AttAtdRec::getEmpID, userId));
//        return attAtdRecMapper.getRecordUserName(startDate, endDate, name, userId);
        return null;
    }

    @Override
    @DS("kqZhongkong")
    public List<BrushCard> getZhongkongRecord(LocalDate startDate, LocalDate endDate, String name, String userId) {
        LambdaQueryWrapper<BrushCard> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ge(BrushCard::getBrushDate, startDate).le(BrushCard::getBrushDate, endDate);
        if (!StringUtils.isEmpty(name)) {
            lambdaQueryWrapper.eq(BrushCard::getUserName, name);
        }
        if (!StringUtils.isEmpty((userId))) {
            lambdaQueryWrapper.eq(BrushCard::getUserId, userId);
        }
        return brushCardMapper.selectList(lambdaQueryWrapper);
/*        return  brushCardMapper.selectList(new LambdaQueryWrapper<BrushCard>()
                .gt(BrushCard::getBrushDate,startDate)
                .lt(BrushCard::getBrushDate,endDate)
                .eq(BrushCard::getUserName,name)
                .eq(BrushCard::getUserId,userId)*/
//        );   
    }

    @Override
    public void sendNotifyPerDay(List<BrushCard> brushCardList, List<AttAtdRec> attAtdRecList) {
        String userName = null;
        String date = null;
        if (brushCardList != null && brushCardList.size() > 0) {
            userName = brushCardList.get(0).getUserName();
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            date = brushCardList.get(0).getBrushDate().format(dtf);
            if (isNeedNotify(brushCardList, attAtdRecList, Const.DayTypeEnum.all)) {
                sendNotify(userName, date, Const.USER_INFO_MAP.get(userName));
            }
        }
    }


    @Override
    public void sendNotifyPerTime(List<BrushCard> brushCardList, List<AttAtdRec> attAtdRecList, Const.DayTypeEnum type) {
        String userName = null;
        String date = null;
        if (brushCardList != null && brushCardList.size() > 0) {
            userName = brushCardList.get(0).getUserName();
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            date = brushCardList.get(0).getBrushDate().format(dtf);
            if (isNeedNotify(brushCardList, attAtdRecList, type)) {
                sendNotify(userName, date, Const.USER_INFO_MAP.get(userName));
            }
        }
    }

    /**
     * 判断打卡记录是否有效
     *
     * @param record
     * @param type
     * @return true：有效
     */
    private boolean isLegalRecord(LocalTime record, Const.DayTypeEnum type) {
        boolean result;
        DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm");
        switch (type) {
            case morning:
                if (Duration.between(record, LocalTime.parse(Const.VALIDATE_TIME_MORNING_BEGIN, df)).getSeconds() <= 0 && Duration.between(record, LocalTime.parse(Const.VALIDATE_TIME_MORNING_END, df)).getSeconds() >= 0) {
                    result = true;
                } else {
                    result = false;
                }
                break;
            case noon:
                if (Duration.between(record, LocalTime.parse(Const.VALIDATE_TIME_NOON_BEGIN, df)).getSeconds() <= 0 && Duration.between(record, LocalTime.parse(Const.VALIDATE_TIME_NOON_END, df)).getSeconds() >= 0) {
                    result = true;
                } else {
                    result = false;
                }
                break;
            case afternoon:
                if (Duration.between(record, LocalTime.parse(Const.VALIDATE_TIME_AFTERNOON_BEGIN, df)).getSeconds() <= 0 && Duration.between(record, LocalTime.parse(Const.VALIDATE_TIME_AFTERNOON_END, df)).getSeconds() >= 0) {
                    result = true;
                } else {
                    result = false;
                }
                break;
            case dusk:
                if (Duration.between(record, LocalTime.parse(Const.VALIDATE_TIME_DUSK_BEGIN, df)).getSeconds() <= 0 && Duration.between(record, LocalTime.parse(Const.VALIDATE_TIME_DUSK_END, df)).getSeconds() >= 0) {
                    result = true;
                } else {
                    result = false;
                }
                break;
            default:
                result = false;
                break;
        }
        return result;

    }

    /**
     * 判断是否需要发送通知
     *
     * @param brushCardList
     * @param attAtdRecList
     * @param type
     * @return
     */
    private boolean isNeedNotify(List<BrushCard> brushCardList, List<AttAtdRec> attAtdRecList, Const.DayTypeEnum type) {
        boolean onWorkRecordMorning = false;
        boolean afterWorkRecordMorning = false;
        boolean onWorkRecordAfternoon = false;
        boolean afterWorkRecordAfternoon = false;

        if (brushCardList != null && brushCardList.size() > 0) {
            for (BrushCard brushCard : brushCardList) {
                LocalTime brushTime = LocalTime.parse(brushCard.getBrushTime(), DateTimeFormatter.ofPattern("HH:mm"));
                if (!onWorkRecordMorning && isLegalRecord(brushTime, Const.DayTypeEnum.morning)) {
                    onWorkRecordMorning = true;
                } else if (!afterWorkRecordMorning && isLegalRecord(brushTime, Const.DayTypeEnum.noon)) {
                    afterWorkRecordMorning = true;
                } else if (!onWorkRecordAfternoon && isLegalRecord(brushTime, Const.DayTypeEnum.afternoon)) {
                    onWorkRecordAfternoon = true;
                } else if (!afterWorkRecordAfternoon && isLegalRecord(brushTime, Const.DayTypeEnum.dusk)) {
                    afterWorkRecordAfternoon = true;
                }
            }
        }

        if (attAtdRecList != null && attAtdRecList.size() > 0) {
            for (AttAtdRec attAtdRec : attAtdRecList) {
                if (isLegalRecord(attAtdRec.getRecTime(), Const.DayTypeEnum.morning)) {
                    onWorkRecordMorning = true;
                } else if (isLegalRecord(attAtdRec.getRecTime(), Const.DayTypeEnum.noon)) {
                    afterWorkRecordMorning = true;
                } else if (isLegalRecord(attAtdRec.getRecTime(), Const.DayTypeEnum.afternoon)) {
                    onWorkRecordAfternoon = true;
                } else if (isLegalRecord(attAtdRec.getRecTime(), Const.DayTypeEnum.dusk)) {
                    afterWorkRecordAfternoon = true;
                }
            }
        }

        if (type.equals(Const.DayTypeEnum.morning)) {
            if (!onWorkRecordMorning || !afterWorkRecordMorning) {
                //发送通知
                return true;
            }
        } else if (type.equals(Const.DayTypeEnum.afternoon)) {
            if (!onWorkRecordAfternoon || !afterWorkRecordAfternoon) {
                //发送通知
                return true;
            }
        } else if (type.equals(Const.DayTypeEnum.all)) {
            if (!onWorkRecordMorning || !afterWorkRecordMorning || !onWorkRecordAfternoon || !afterWorkRecordAfternoon) {
                //发送通知
                return true;
            }
        }
        return false;
    }

    private void sendNotify(String userName, String date, String phoneNumbers) {
        Map<String, String> params = new HashMap<>(6);
        params.put("date", date);
        params.put("name", userName);
        params.put("phoneNumbers", phoneNumbers);
        try {
            HttpsUtilsPool.get(Const.NOTIFY_SMS_API_URL, null, params);
        } catch (Exception e) {
            logger.error("发送通知出现异常:" + e.getMessage());
        }
    }
}
